use crate::REQWEST_CLIENT;
use anyhow::{ ensure, Result };
use serde::{ Deserialize, Serialize };
use serde_json::Value;
/// 百分比报表 Mapping to [RPT_F10_FINANCE_BRATIO.json](file:///Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/eastmoney/sample/RPT_F10_FINANCE_BRATIO.json)
#[derive(Debug, Serialize, Deserialize)]
pub struct RptF10FinanceBratio {
    pub version: Value,
    pub result: RptF10FinanceBratioResult,
    pub success: Value,
    pub message: Value,
    pub code: Value,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RptF10FinanceBratioResult {
    pub pages: Value,
    pub data: Vec<RptF10FinanceBratioResultData>,
    pub count: Option<Value>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RptF10FinanceBratioResultData {
    #[serde(rename = "SECUCODE")]
    pub secucode: Option<Value>, // 证券代码
    #[serde(rename = "SECURITY_CODE")]
    pub security_code: Option<Value>, // 证券代码
    #[serde(rename = "SECURITY_NAME_ABBR")]
    pub security_name_abbr: Option<Value>, // 证券简称
    #[serde(rename = "ORG_CODE")]
    pub org_code: Option<Value>, // 机构代码
    #[serde(rename = "ORG_TYPE")]
    pub org_type: Option<Value>, // 机构类型
    #[serde(rename = "REPORT_DATE")]
    pub report_date: Option<Value>, // 报告日期
    #[serde(rename = "SECURITY_TYPE_CODE")]
    pub security_type_code: Option<Value>, // 证券类型代码
    #[serde(rename = "NOTICE_DATE")]
    pub notice_date: Option<Value>, // 公告日期
    #[serde(rename = "UPDATE_DATE")]
    pub update_date: Option<Value>, // 更新日期
    #[serde(rename = "CURRENCY")]
    pub currency: Option<Value>, // 货币
    #[serde(rename = "OPERATE_INCOME")]
    pub operate_income: Option<Value>, // 营业收入
    #[serde(rename = "INTEREST_NI")]
    pub interest_ni: Option<Value>, // 利息净收入
    #[serde(rename = "FEE_COMMISSION_NI")]
    pub fee_commission_ni: Option<Value>, // 手续费及佣金净收入
    #[serde(rename = "INVEST_INCOME")]
    pub invest_income: Option<Value>, // 投资收益
    #[serde(rename = "FAIRVALUE_CHANGE_INCOME")]
    pub fairvalue_change_income: Option<Value>, // 公允价值变动收益
    #[serde(rename = "EXCHANGE_INCOME")]
    pub exchange_income: Option<Value>, // 汇兑收益
    #[serde(rename = "OTHER_BUSINESS_INCOME")]
    pub other_business_income: Option<Value>, // 其他业务收入
    #[serde(rename = "OPERATE_EXPENSE")]
    pub operate_expense: Option<Value>, // 营业支出
    #[serde(rename = "OPERATE_TAX_ADD")]
    pub operate_tax_add: Option<Value>, // 营业税金及附加
    #[serde(rename = "BUSINESS_MANAGE_EXPENSE")]
    pub business_manage_expense: Option<Value>, // 业务管理费用
    #[serde(rename = "ASSET_IMPAIRMENT_LOSS")]
    pub asset_impairment_loss: Option<Value>, // 资产减值损失
    #[serde(rename = "OTHER_BUSINESS_COST")]
    pub other_business_cost: Option<Value>, // 其他业务成本
    #[serde(rename = "OPERATE_PROFIT")]
    pub operate_profit: Option<Value>, // 营业利润
    #[serde(rename = "NONBUSINESS_INCOME")]
    pub nonbusiness_income: Option<Value>, // 营业外收入
    #[serde(rename = "NONBUSINESS_EXPENSE")]
    pub nonbusiness_expense: Option<Value>, // 营业外支出
    #[serde(rename = "TOTAL_PROFIT")]
    pub total_profit: Option<Value>, // 利润总额
    #[serde(rename = "INCOME_TAX")]
    pub income_tax: Option<Value>, // 所得税费用
    #[serde(rename = "NETPROFIT")]
    pub netprofit: Option<Value>, // 净利润
    #[serde(rename = "ASSET_DISPOSAL_INCOME")]
    pub asset_disposal_income: Option<Value>, // 资产处置收益
    #[serde(rename = "OTHER_INCOME")]
    pub other_income: Option<Value>, // 其他收益
    #[serde(rename = "CREDIT_IMPAIRMENT_LOSS")]
    pub credit_impairment_loss: Option<Value>, // 信用减值损失
}

impl RptF10FinanceBratio {
    /// 百分比报表 RPT_F10_FINANCE_BRATIO 按报告期
    /// Referer: https://emweb.securities.eastmoney.com/pc_hsf10/pages/index.html?type=web&code=SZ000001&color=b#/cwfx/bfbbb
    ///
    /// data: https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_FINANCE_BRATIO&columns=SECUCODE%2CSECURITY_CODE%2CSECURITY_NAME_ABBR%2CORG_CODE%2CORG_TYPE%2CREPORT_DATE%2CSECURITY_TYPE_CODE%2CNOTICE_DATE%2CUPDATE_DATE%2CCURRENCY%2COPERATE_INCOME%2CINTEREST_NI%2CFEE_COMMISSION_NI%2CINVEST_INCOME%2CFAIRVALUE_CHANGE_INCOME%2CEXCHANGE_INCOME%2COTHER_BUSINESS_INCOME%2COPERATE_EXPENSE%2COPERATE_TAX_ADD%2CBUSINESS_MANAGE_EXPENSE%2CASSET_IMPAIRMENT_LOSS%2COTHER_BUSINESS_COST%2COPERATE_PROFIT%2CNONBUSINESS_INCOME%2CNONBUSINESS_EXPENSE%2CTOTAL_PROFIT%2CINCOME_TAX%2CNETPROFIT%2CASSET_DISPOSAL_INCOME%2COTHER_INCOME%2CCREDIT_IMPAIRMENT_LOSS&quoteColumns=&filter=(SECUCODE%3D%22000001.SZ%22)&sortTypes=-1%2C1&sortColumns=REPORT_DATE%2CINTERFACE_TYPE&pageNumber=1&pageSize=12&source=HSF10&client=PC&v=06295809486287134
    pub async fn rpt_f10_finance_bratio(_code: &str) -> Result<RptF10FinanceBratio> {
        // Query String Parameters:
        //
        // reportName: RPT_F10_FINANCE_BRATIO
        // columns: SECUCODE,SECURITY_CODE,SECURITY_NAME_ABBR,ORG_CODE,ORG_TYPE,REPORT_DATE,SECURITY_TYPE_CODE,NOTICE_DATE,UPDATE_DATE,CURRENCY,OPERATE_INCOME,INTEREST_NI,FEE_COMMISSION_NI,INVEST_INCOME,FAIRVALUE_CHANGE_INCOME,EXCHANGE_INCOME,OTHER_BUSINESS_INCOME,OPERATE_EXPENSE,OPERATE_TAX_ADD,BUSINESS_MANAGE_EXPENSE,ASSET_IMPAIRMENT_LOSS,OTHER_BUSINESS_COST,OPERATE_PROFIT,NONBUSINESS_INCOME,NONBUSINESS_EXPENSE,TOTAL_PROFIT,INCOME_TAX,NETPROFIT,ASSET_DISPOSAL_INCOME,OTHER_INCOME,CREDIT_IMPAIRMENT_LOSS
        // quoteColumns:
        // filter: (SECUCODE="000001.SZ")
        // sortTypes: -1,1
        // sortColumns: REPORT_DATE,INTERFACE_TYPE
        // pageNumber: 1
        // pageSize: 12
        // source: HSF10
        // client: PC
        // v: 001522325182627049

        let request_url = format!(
            "https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_FINANCE_BRATIO&columns=SECUCODE%2CSECURITY_CODE%2CSECURITY_NAME_ABBR%2CORG_CODE%2CORG_TYPE%2CREPORT_DATE%2CSECURITY_TYPE_CODE%2CNOTICE_DATE%2CUPDATE_DATE%2CCURRENCY%2COPERATE_INCOME%2CINTEREST_NI%2CFEE_COMMISSION_NI%2CINVEST_INCOME%2CFAIRVALUE_CHANGE_INCOME%2CEXCHANGE_INCOME%2COTHER_BUSINESS_INCOME%2COPERATE_EXPENSE%2COPERATE_TAX_ADD%2CBUSINESS_MANAGE_EXPENSE%2CASSET_IMPAIRMENT_LOSS%2COTHER_BUSINESS_COST%2COPERATE_PROFIT%2CNONBUSINESS_INCOME%2CNONBUSINESS_EXPENSE%2CTOTAL_PROFIT%2CINCOME_TAX%2CNETPROFIT%2CASSET_DISPOSAL_INCOME%2COTHER_INCOME%2CCREDIT_IMPAIRMENT_LOSS&quoteColumns=&filter=(SECUCODE%3D%22000001.SZ%22)&sortTypes=-1%2C1&sortColumns=REPORT_DATE%2CINTERFACE_TYPE&pageNumber=1&pageSize=12&source=HSF10&client=PC&v=06295809486287134"
        );

        let response = REQWEST_CLIENT.get(request_url)
            .header(reqwest::header::ACCEPT, "*/*")
            .header(reqwest::header::ACCEPT_ENCODING, "gzip, deflate, br")
            .header(reqwest::header::ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9,en;q=0.8")
            .header(reqwest::header::CACHE_CONTROL, "no-cache")
            .header(reqwest::header::CONNECTION, "keep-alive")
            // .header(reqwest::header::COOKIE, "qgqp_b_id=d6299473145338f68687834ba37fa719; st_si=77687174285423; AUTH_FUND.EASTMONEY.COM_GSJZ=AUTH*TTJJ*TOKEN; EMFUND0=01-16%2016%3A57%3A06@%23%24%u4E2D%u822A%u65B0%u8D77%u822A%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408A@%23%24005537; EMFUND1=01-16%2017%3A04%3A53@%23%24%u91D1%u4FE1%u6D88%u8D39%u5347%u7EA7%u80A1%u7968A@%23%24006692; EMFUND2=01-16%2020%3A01%3A56@%23%24%u5357%u65B9%u4E0A%u8BC1380ETF@%23%24510290; EMFUND3=01-29%2015%3A02%3A07@%23%24%u534E%u590F%u4E2D%u8BC1%u5168%u6307%u623F%u5730%u4EA7ETF@%23%24515060; EMFUND4=01-30%2014%3A41%3A22@%23%24%u534E%u6CF0%u67CF%u745E%u6D88%u8D39%u6210%u957F%u6DF7%u5408@%23%24001069; EMFUND5=01-30%2014%3A45%3A59@%23%24%u5E7F%u53D1%u6052%u751F%u6D88%u8D39%28QDII-ETF%29@%23%24159699; EMFUND6=01-30%2014%3A47%3A24@%23%24%u5357%u65B9%u7EA2%u5229%u4F4E%u6CE250ETF@%23%24515450; EMFUND7=01-31%2015%3A21%3A23@%23%24%u56FD%u8054%u4E2D%u8BC1%u7164%u70AD%u6307%u6570%28LOF%29A@%23%24168204; EMFUND8=02-02%2008%3A34%3A56@%23%24%u666F%u987A%u957F%u57CE%u652F%u67F1%u4EA7%u4E1A%u6DF7%u5408@%23%24260117; EMFUND9=02-02 10:30:22@#$%u897F%u90E8%u5229%u5F97%u805A%u79BE%u6DF7%u5408A@%23%24007423; st_asi=delete; HAList=ty-1-513130-%u6052%u751F%u79D1%u6280ETF%2Cty-0-300078-%u601D%u521B%u533B%u60E0%2Cty-0-300486-%u4E1C%u6770%u667A%u80FD%2Cty-1-513360-%u6559%u80B2ETF%2Cty-0-300478-%u676D%u5DDE%u9AD8%u65B0%2Cty-0-301589-N%u8BFA%u74E6%2Cty-1-603135-%u4E2D%u91CD%u79D1%u6280%2Cty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-0-002400-%u7701%u5E7F%u96C6%u56E2%2Cty-1-601127-%u8D5B%u529B%u65AF; st_pvi=47260449691882; st_sp=2024-01-12%2017%3A28%3A27; st_inirUrl=https%3A%2F%2Fwww.google.com.hk%2F; st_sn=438; st_psi=20240226102321941-113200301321-9024721593")
            .header(reqwest::header::HOST, "datacenter.eastmoney.com")
            .header(reqwest::header::ORIGIN, "https://emweb.securities.eastmoney.com")
            .header(reqwest::header::PRAGMA, "no-cache")
            .header(reqwest::header::REFERER, "https://emweb.securities.eastmoney.com/")
            .header(
                reqwest::header::USER_AGENT,
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
            )
            .header(
                "Sec-Ch-Ua",
                "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
            )
            .header("Sec-Ch-Ua-Mobile", "?0")
            .header("Sec-Ch-Ua-Platform", "\"macOS\"")
            .header("Sec-Fetch-Dest", "empty")
            .header("Sec-Fetch-Mode", "cors")
            .header("Sec-Fetch-Site", "same-origin")
            .send().await?;

        let body = response.text().await?;

        // println!("*** body={}\n\nhangqin\n\n", body);

        let fund: RptF10FinanceBratio = serde_json::from_str(&body)?;

        // println!("{:?}", fund);

        Ok(fund)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn test_stock_rpt_f10_finance_bratio() {
        let result = RptF10FinanceBratio::rpt_f10_finance_bratio("000001.SZ").await;

        assert_eq!(result.is_ok(), true);
        if let Ok(bratio) = result {
            assert_eq!(bratio.message.as_str(), Some("ok"));
            println!("{:?}\n", bratio);
        }
    }
}
